package com.sh.sales.happysales.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sh.polymedicine.happysale.net.entity.CashList;
import com.sh.polymedicine.happysale.result.PageResult;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.result.WalletResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.adapter.HiswolletAdapter;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.MyListener;
import com.sh.sales.happysales.view.NewToast;
import com.sh.sales.happysales.view.PullToRefreshLayout;
import com.sh.sales.happysales.view.PullableListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/15.
 */

public class WalletActivity extends BaseActivity implements LoginObsever {
    @BindView(R.id.set_back)
    ImageView setBack;
    @BindView(R.id.profect_next)
    TextView profectNext;
    @BindView(R.id.wallet_value)
    TextView walletValue;
    @BindView(R.id.wallet_click)
    LinearLayout walletClick;
    @BindView(R.id.pull_icon)
    ImageView pullIcon;
    @BindView(R.id.refreshing_icon)
    ImageView refreshingIcon;
    @BindView(R.id.state_tv)
    TextView stateTv;
    @BindView(R.id.state_iv)
    ImageView stateIv;
    @BindView(R.id.head_view)
    RelativeLayout headView;
    @BindView(R.id.content_view)
    PullableListView contentView;
    @BindView(R.id.pullup_icon)
    ImageView pullupIcon;
    @BindView(R.id.loading_icon)
    ImageView loadingIcon;
    @BindView(R.id.loadstate_tv)
    TextView loadstateTv;
    @BindView(R.id.loadstate_iv)
    ImageView loadstateIv;
    @BindView(R.id.loadmore_view)
    RelativeLayout loadmoreView;
    @BindView(R.id.refresh_view)
    PullToRefreshLayout refreshView;
    @BindView(R.id.wallet_histotal)
    TextView wallethistotal;

    private HiswolletAdapter mAdapter;
    private Context mContext;
    private List<CashList> cashs;

    private Subscriber<WalletResult> mWalletSubscriber;
    private Subscriber<PageResult<CashList>> mCashListSubscriber;
    private String TAG = "WalletActivity";


    private double Total = 0;
    private double mSurplus = 0;
    private int pageNo = 1;
    private int pageSize = 20;
    private String userSign;
    private boolean lastPage;

    private int refreshUserSignTag = -1;
    private UserInfoResult mUser;
    private int userId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        ButterKnife.bind(this);
        mContext = this;
        mAppManager.addActivity(this);
        mLoginObserable.registerObserver(this);
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        cashs = new ArrayList<>();
        mAdapter = new HiswolletAdapter(mContext, cashs);
        contentView.setAdapter(mAdapter);
        refreshView.setOnRefreshListener(new PullListener());
        mUser = AppData.getInstence().getmUserInfoResult();
        userId = AppData.getInstence().getmUserToken().getUserId();
        addListener();
        walleteShow();
        cashList();
    }

    private void walleteShow() {
        refreshUserSignTag = 1;
        if (mWalletSubscriber != null) {
            if (mWalletSubscriber.isUnsubscribed()) {
                mWalletSubscriber.unsubscribe();
            }
        }
        mWalletSubscriber = new Subscriber<WalletResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError:" + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(mContext, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(WalletActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(mContext, e.getCause().getMessage());
                } else {
                    NewToast.makeText(mContext, "获取钱包信息失败，请检查网络");
                }
            }

            @Override
            public void onNext(WalletResult mWalletResult) {
                Total = mWalletResult.getTotal();
                mSurplus = mWalletResult.getSurplus();
                walletValue.setText(mWalletResult.getSurplus() + "");
                wallethistotal.setText(mWalletResult.getTotal() + "元");
            }
        };
        mHappySaleManager.mineWallet(userId + "", userSign, mWalletSubscriber).subscribe(mWalletSubscriber);

    }


    private void cashList() {

        mCashListSubscriber = new Subscriber<PageResult<CashList>>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError:" + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(mContext, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(WalletActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(mContext, e.getCause().getMessage());
                } else {
                    NewToast.makeText(mContext, "获取提现历史，请检查网络");
                }
            }

            @Override
            public void onNext(PageResult<CashList> pageResult) {
                refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                lastPage = pageResult.isLastPage();
                if (pageResult.getList() != null && (pageResult.getList().size() > 0)) {
                    setList(pageResult);
                } else {
                    NewToast.makeText(WalletActivity.this, "数据为空");
                }
            }
        };
        mHappySaleManager.cashList(pageNo + "", "" + pageSize, userSign, mCashListSubscriber).subscribe(mCashListSubscriber);


    }

    private void setList(PageResult<CashList> pageResult) {
        if (pageNo == 1) {
            cashs.clear();
        }
        cashs.add((CashList) pageResult.getList());
        mAdapter.notifyDataSetChanged();
    }

    private void addListener() {
        refreshView.setOnRefreshListener(new MyListener());
    }

    @OnClick({R.id.set_back, R.id.wallet_click})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_back:
                mAppManager.finishActivity(this);
                break;
            case R.id.wallet_click:
                if (mSurplus == 0) {
                    NewToast.makeText(WalletActivity.this, "暂无可提现金");
                    return;
                }
                Intent in = new Intent();
                in.putExtra("cashValue", mSurplus);
                in.setClass(WalletActivity.this, CashToWechatActivity.class);
                startActivity(in);
                break;
        }
    }

    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshUserSignTag) {
            case 1:
                walleteShow();
                break;
            case 2:
                cashList();
                break;
        }
    }

    class PullListener implements PullToRefreshLayout.OnRefreshListener {


        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {

        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

            if (!lastPage) {
                pageNo = pageNo + 1;
                mHappySaleManager.cashList(pageNo + "", "" + pageSize, userSign, mCashListSubscriber).subscribe(mCashListSubscriber);
            } else {
                NewToast.makeText(WalletActivity.this, "没有更多数据");
                refreshView.loadmoreFinish(PullToRefreshLayout.DONE);
            }

        }
    }

    @Override
    protected void onResume() {
        mHappySaleManager.mineWallet(userId + "", userSign, mWalletSubscriber).subscribe(mWalletSubscriber);
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }
}
